package com.example.chartgpt.service;

import com.example.chartgpt.model.Messages;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.stereotype.Service;

@Service
public class ReplyContentImp implements IReplyContent {

    @Override
    public String extractLastReplyContent(String answer) throws JsonProcessingException {
        ObjectMapper objectMapper = new ObjectMapper();
        JsonNode responseJson = objectMapper.readTree(answer);

        // 假设响应的 "choices" 字段是一个数组，并且最后一个回复的内容在数组的第一个元素中
        JsonNode choices = responseJson.get("choices");
        if (choices.isArray() && choices.size() > 0) {
            JsonNode lastChoice = choices.get(choices.size() - 1);
            JsonNode message = lastChoice.get("message");
            if (message != null) {
                JsonNode content = message.get("content");
                if (content != null) {
                    return content.asText();
                }
            }
        }
        return null;
    }


    @Override
    public Messages addMessageToConversationHistory(String role, String content) {
        Messages messages = new Messages();
        messages.setRole(role);
        messages.setContent(content);
        return messages;
    }


}
